<template>
  <div class="ai-assistant-container">
    <!-- 聊天窗口 -->
    <div class="chat-window" v-show="isChatOpen">
      <div class="chat-header">
        <div class="chat-title">
          <i class="iconfont">&#xe607;</i>
          <span>智能客服助手</span>
        </div>
        <div class="chat-actions">
          <i class="iconfont close-icon" @click="toggleChatWindow">&#xe614;</i>
        </div>
      </div>

      <div class="chat-messages" ref="messagesContainer">
        <div v-for="(message, index) in messages" :key="index" :class="['message', message.type]">
          <div class="message-avatar" v-if="message.type === 'ai'">
            <i class="iconfont">&#xe836;</i>
          </div>
          <div class="message-content">
             <!-- 修改：AI消息使用markdown渲染，用户消息保持原样 -->
            <div v-if="message.type === 'ai'" class="message-text markdown-body" v-html="message.html"></div>
            <div v-else class="message-text">{{ message.text }}</div>
          </div>
          
          <div class="message-avatar user-avatar" v-if="message.type === 'user'">
            <i class="iconfont">&#xe609;</i>
          </div>
        </div>
        <div class="typing-indicator" v-if="isTyping">
          <span style="font-size: small;">正在思考</span>
          <div class="dot"></div>
          <div class="dot"></div>
          <div class="dot"></div>
        </div>
      </div>

      <div class="chat-input">
        <el-input v-model="userInput" placeholder="请输入您的问题..." :disabled="isTyping" @keyup.enter="sendMessage" />
        <div class="send-button" @click="sendMessage" :class="{ disabled: isTyping || !userInput.trim() }">
          <i class="iconfont">&#x100bd;</i>
        </div>
      </div>
    </div>

    <div class="assistant-button" @click="toggleChatWindow">
      <div class="avatar-placeholder">
        <img src="@/assets/pic/机器人.png">
      </div>
      <div class="button-text">智能助手</div>
    </div>
  </div>

</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue';
import { marked } from 'marked';
import { markedHighlight } from 'marked-highlight';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
import axios from 'axios';

// 配置 marked - 使用 markedHighlight 扩展
marked.use(markedHighlight({
  langPrefix: 'hljs language-',
  highlight(code, lang) {
    const language = hljs.getLanguage(lang) ? lang : 'plaintext';
    return hljs.highlight(code, { language }).value;
  }
}));

// 配置其他 marked 选项
marked.setOptions({
  breaks: true,
  gfm: true
});

// 聊天窗口状态
const isChatOpen = ref(false);
const userInput = ref('');
const isTyping = ref(false);
const messagesContainer = ref<HTMLElement | null>(null);

// 模拟消息数据
interface Message {
  text: string;
  type: 'user' | 'ai';
  time: string;
  html?: string; // AI消息的HTML渲染内容
}

const messages = reactive<Message[]>([
  {
    text: '您好！我是智能客服助手，有什么可以帮您的吗？',
    type: 'ai',
    time: formatTime(new Date()),
    html: marked('您好！我是智能客服助手，有什么可以帮您的吗？') as string
  }
]);

// 格式化时间
function formatTime(date: Date): string {
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
}

// 切换聊天窗口
function toggleChatWindow() {
  isChatOpen.value = !isChatOpen.value;
}


// 发送消息
async function sendMessage() {
  if (!userInput.value.trim() || isTyping.value) return;

  // 添加用户消息
  const userMessage: Message = {
    text: userInput.value,
    type: 'user',
    time: formatTime(new Date())
  };
  messages.push(userMessage);

  // 保存问题并清空输入框
  const question = userInput.value;
  userInput.value = '';

  // 显示AI正在输入
  isTyping.value = true;

  // 创建一个空的AI消息用于实时更新
  const aiMessage: Message = {
    text: '',
    type: 'ai',
    time: formatTime(new Date()),
    html: ''
  };
  
  // 滚动到底部
  await nextTick();
  scrollToBottom();

  try {
    // 使用 Axios 替代 EventSource
    const response = await axios.get(
      `http://localhost:8089/ai/bailian/knowledge/generate?message=${encodeURIComponent(question)}`
    );
    
    // 获取AI回复内容
    aiMessage.text = response.data;
    
    // 将 Markdown 转换为 HTML
    aiMessage.html = marked(aiMessage.text) as string;
    
    // 添加消息到列表
    messages.push(aiMessage);
    
    // 滚动到底部
    await nextTick();
    scrollToBottom();
    
  } catch (error) {
    console.error('Error:', error);
    aiMessage.text = '抱歉，发生了错误，请稍后重试。';
    aiMessage.html = marked(aiMessage.text) as string;
    messages.push(aiMessage);
  } finally {
    // 无论成功或失败，都结束输入状态
    isTyping.value = false;
  }
}
// 滚动到底部
function scrollToBottom() {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
}

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  scrollToBottom();
}, { deep: true });

// 组件挂载后滚动到底部
onMounted(() => {
  scrollToBottom();
});
</script>

<style scoped lang="less">
/* 在线链接服务仅供平台体验和调试使用，平台不承诺服务的稳定性，企业客户需下载字体包自行发布使用并做好备份。 */
@font-face {
  font-family: 'iconfont';
  /* Project id 4410292 */
  src:
    url('//at.alicdn.com/t/c/font_4410292_1jw0x45n12r.woff2?t=1760269361337') format('woff2'),
    url('//at.alicdn.com/t/c/font_4410292_1jw0x45n12r.woff?t=1760269361337') format('woff'),
    url('//at.alicdn.com/t/c/font_4410292_1jw0x45n12r.ttf?t=1760269361337') format('truetype');
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -webkit-text-stroke-width: 0.2px;
  -moz-osx-font-smoothing: grayscale;
}

// 新增：markdown样式
.markdown-body {
  :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
    margin-top: 10px;
    margin-bottom: 8px;
    font-weight: 600;
  }

  :deep(p) {
    margin-bottom: 8px;
  }

  :deep(code) {
    background-color: rgba(0, 0, 0, 0.05);
    padding: 2px 4px;
    border-radius: 3px;
    font-family: 'Courier New', monospace;
    font-size: 0.9em;
  }

  :deep(pre) {
    background-color: #f6f8fa;
    padding: 10px;
    border-radius: 6px;
    overflow-x: auto;
    margin: 8px 0;

    code {
      background-color: transparent;
      padding: 0;
    }
  }

  :deep(ul), :deep(ol) {
    padding-left: 20px;
    margin: 8px 0;
  }

  :deep(li) {
    margin-bottom: 4px;
  }

  :deep(blockquote) {
    border-left: 3px solid #ddd;
    padding-left: 10px;
    margin: 8px 0;
    color: #666;
  }

  :deep(a) {
    color: #1890ff;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }

  :deep(table) {
    border-collapse: collapse;
    width: 100%;
    margin: 8px 0;

    th, td {
      border: 1px solid #ddd;
      padding: 6px 8px;
      text-align: left;
    }

    th {
      background-color: #f6f8fa;
      font-weight: 600;
    }
  }
}

.ai-assistant-container {
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 1000;
  display: flex;
  /* 修改对齐方式 */
  align-items: flex-end;
  gap: 16px;
}

.assistant-button {
  width: 45px;
  height: 142px;
  /* 调整为垂直矩形 */
  border-radius: 21px;
  /* 圆角 */
  background-color: #1890ff;
  color: white;
  display: flex;
  flex-direction: column;
  /* 垂直排列内部元素 */
  justify-content: space-evenly;
  /* 均匀分布 */
  align-items: center;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
  }

  /* 移除 active 状态下的背景色变化 */
  /* &.active {
    background-color: #f56c6c;
  } */
}

/* 新增：圆形图片占位符样式 */
.avatar-placeholder {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: white;
  color: #1890ff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-placeholder img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  /* 裁剪并填充容器，保持宽高比 */
}

/* 新增：垂直文字样式 */
.button-text {
  font-size: 15px;
  // font-weight: bold;
  writing-mode: vertical-rl;
  /* 文字竖排 */
  letter-spacing: 8px;
  /* 增加文字间距 */
  color: white;
}

.chat-window {
  position: absolute;
  bottom: 0;
  /* 修改 bottom 使其与按钮底部对齐 */
  right: 80px;
  /* 调整 right 值，使其在按钮左侧 */
  width: 350px;
  height: 500px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  /* 新增过渡效果 */
  transform-origin: bottom right;
  transition: transform 0.3s ease, opacity 0.3s ease;
}

/* 新增：聊天窗口关闭时的状态 */
.chat-window:not([style*="display: none;"]) {
  transform: scale(1);
  opacity: 1;
}

.chat-window[style*="display: none;"] {
  transform: scale(0.9);
  opacity: 0;
  pointer-events: none;
}

.chat-header {
  padding: 15px;
  background-color: white;
  // color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .chat-title {
    display: flex;
    align-items: center;
    gap: 8px;

    .iconfont {
      font-size: 20px;
    }

    span {
      font-size: 16px;
      font-weight: 500;
    }
  }

  .chat-actions {
    .close-icon {
      cursor: pointer;
      font-size: 18px;

      &:hover {
        opacity: 0.8;
      }
    }
  }
}

.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f9f9f9;
  display: flex;
  flex-direction: column;
  gap: 15px;

  .message {
    display: flex;
    margin-bottom: 10px;


    &.user {
      align-self: flex-end;
      flex-direction: row-reverse;

      .message-content {
        background-color: #1890ff;
        color: white;
        border-radius: 18px 18px 4px 18px;
      }
    }

    &.ai {
      align-self: flex-start;

      .message-content {
        background-color: white;
        border-radius: 18px 18px 18px 4px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }

    .message-avatar {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      // background-color: #1890ff;
      color: white;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 0 8px;

      .iconfont {
        font-size: 50px; // 增加图标大小，默认是16px
      }

      &.user-avatar .iconfont{
        font-size: 20px !important;
      }
    }

    .message-content {
      padding: 10px 15px;

      .message-text {
        font-size: 14px;
        line-height: 1.5;
        word-break: break-word;
      }

      .message-time {
        font-size: 12px;
        opacity: 0.7;
        margin-top: 4px;
        text-align: right;
      }
    }
  }

  .typing-indicator {
    display: flex;
    align-items: center;
    align-self: flex-start;
    background-color: #e6e6e6;
    padding: 8px 12px;
    border-radius: 18px;
    margin-left: 8px;

    .dot {
      width: 4px;
      height: 4px;
      background-color: #999;
      border-radius: 50%;
      margin: 0 2px;
      animation: typing 1.5s infinite ease-in-out;

      &:nth-child(1) {
        animation-delay: 0s;
      }

      &:nth-child(2) {
        animation-delay: 0.2s;
      }

      &:nth-child(3) {
        animation-delay: 0.4s;
      }
    }
  }
}

.chat-input {
  padding: 15px;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
  gap: 10px;

  :deep(.el-input__wrapper) {
    background-color: #f5f5f5;
    border-radius: 20px;
  }

  .send-button {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #1890ff;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: all 0.3s ease;
    flex-shrink: 0;

    .iconfont {
      color: white;
      font-size: 20px;
    }

    &:hover:not(.disabled) {
      background-color: #40a9ff;
      transform: scale(1.05);
    }

    &.disabled {
      background-color: #d9d9d9;
      cursor: not-allowed;
      opacity: 0.6;
    }
  }
}

@keyframes typing {
  0% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-5px);
  }

  100% {
    transform: translateY(0);
  }
}
</style>